<template>
  <div class="class">
    <el-container class="main" style="padding: 20px">
      <el-header class="Header">
        <el-row type="flex" justify="space-between">
          <el-form ref="form" label-width="80px" :model="formDateTow">
            <el-input
              v-model="formDateTow.class_name"
              placeholder="班级名称"
              style="width: 208px"
            />
            <el-select
              v-model="formDateTow.subject_id"
              placeholder="归属学科"
              style="padding: 0 20px"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-select
              v-model="formDateTow.state"
              placeholder="显示状态"
              style="padding-right: 20px"
            >
              <el-option
                v-for="item in optionsTow"
                :key="item.state"
                :label="item.label"
                :value="item.state"
              />
            </el-select>
            <el-button type="primary" plain @click="btnSearch">搜索</el-button>
            <el-button type="primary" plain @click="btnClan">重置</el-button>
          </el-form>
          <el-button
            type="primary"
            plain
            size="medium"
            @click="btnAdd"
          >创建班级</el-button>
        </el-row>
      </el-header>
      <el-main class="Main">
        <el-table
          ref="singleTable"
          :data="tableData"
          highlight-current-row
          style="width: 100%"
          border
        >
          <el-table-column label="#" width="60" type="expand">
            <template slot-scope="{ row }">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="班级名称">
                  <span class="Names">{{ row.class_name }}</span>
                </el-form-item>
                <el-form-item label="归属学科">
                  <span class="Names">{{ row.subject_name }}</span>
                </el-form-item>
                <el-form-item label="创建人">
                  <span class="Names">{{ row.username }}</span>
                </el-form-item>
                <el-form-item label="开始结束日期">
                  <span
                    class="Names"
                  >{{ row.start_time | formatDate }} 至
                    {{ row.end_time | formatDate }}</span>
                </el-form-item>
                <el-form-item label="创建日期">
                  <span class="Names">{{ row.created_at }}</span>
                </el-form-item>
                <el-form-item label="讲师">
                  <span class="Names">
                    <el-tag size="medium" type="success">
                      {{ JSON.parse(row.teacher_info).map(val=>{ return val.username}).join(',') }}
                    </el-tag>
                  </span>
                </el-form-item>
                <el-form-item label="助教">
                  <span class="Names">
                    <el-tag size="medium" type="success">
                      {{ JSON.parse(row.zhujiao_info).map(val=>{ return val.username}).join(',') }}
                    </el-tag>
                  </span>
                </el-form-item>
                <el-form-item label="班主任">

                  <span class="Names">
                    <el-tag size="medium" type="success">
                      {{ JSON.parse(row.manager_info).map(val=>{ return val.username}).join(',') }}
                    </el-tag>
                  </span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column property="creator_id" label="班级ID" width="70" />
          <el-table-column property="class_name" label="班级名称" width="200" />
          <el-table-column
            property="subject_name"
            label="归属学科"
            width="160"
          />
          <el-table-column property="teacher_info" label="讲师" width="150">
            <template slot-scope="{row}">
              <el-tag size="medium" type="success">{{ JSON.parse(row.teacher_info).map(val=>{ return val.username}).join(',') }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column property="zhujiao_info" label="助教" width="150">
            <template slot-scope="{row}">
              <el-tag size="medium" type="success">{{ JSON.parse(row.zhujiao_info).map(val=>{ return val.username}).join(',') }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column property="manager_info" label="班主任" width="150">
            <template slot-scope="{row}">
              <el-tag size="medium" type="success">{{ JSON.parse(row.manager_info).map(val=>{ return val.username}).join(',') }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column property="username" label="创建人" width="140" />
          <el-table-column property="subject_id" label="是否显示" width="120">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.state"
                active-color="#409eff"
                inactive-color="#666"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="2"
                @change="switchChange(row.id, row.state)"
              />
            </template>
          </el-table-column>
          <el-table-column label="开始结束日期" width="240">
            <template
              slot-scope="{ row }"
            >{{ row.start_time | formatDate }} 至
              {{ row.end_time | formatDate }}</template>
          </el-table-column>
          <el-table-column property="created_at" label="创建日期" width="160" />
          <el-table-column
            property="address"
            label="操作"
            width="200"
            fixed="right"
          >
            <template slot-scope="{ row }">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="btnEdit(row.id)"
              />
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="btnDel(row.id)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <!-- 分页 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        background
        :current-page="page.page"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="page.limit"
        layout="total, sizes, prev, pager, next"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>
    <!-- 弹窗 -->
    <el-dialog v-if="dialogshow" :title="formDate.id?'编辑':'新增'" :visible.sync="dialogFormVisible" @close="btnClear">
      <el-form ref="formDate" :inline="true" :model="formDate" :rules="rules" style="padding-left: 30px">
        <el-form-item label="归属学科" prop="subject_id">
          <el-select v-model="formDate.subject_id" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" style="padding-left: 50px" prop="class_name">
          <el-input
            v-model="formDate.class_name"
            placeholder="请输入班级名称"
            style="width: 208px"
          />
        </el-form-item>
        <el-form-item label="授课老师">
          <el-select
            v-model="formDate.teacher_info"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="(item,index) in tableinfo"
              :key="item.user_id"
              :label="item.username"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="助教老师" style="padding-left: 50px">
          <el-select
            v-model="formDate.zhujiao_info"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="(item,index) in zhujiaoinfo"
              :key="item.user_id"
              :label="item.username"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班主任">
          <el-select
            v-model="formDate.manager_info"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="(item,index) in managerinfo"
              :key="item.user_id"
              :label="item.username"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开课日期" style="padding-left: 58px">
          <el-date-picker
            v-model="formDate.value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            v-model="formDate.sort"
            :min="1"
            :max="100"
            label="描述文字"
          />
        </el-form-item>
        <el-form-item label="班级状态" style="padding-left: 100px">
          <el-switch
            v-model="formDate.state"
            active-text="正常"
            inactive-text="关闭"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
      </el-form>
      <el-row style="margin-left:100px">
        <el-button @click="btnClear">取消</el-button>
        <el-button type="primary" @click="btnOk">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {
  getClass,
  delClass,
  subJect,
  postStatus,
  teacherClass,
  zhujiaoClass,
  managerClass,
  amendClass,
  AddClass,
  editClass
} from '@/api/class'

export default {
  name: 'Class',
  components: {},
  props: {},
  data() {
    return {
      dialogFormVisible: false,
      formDate: {
        subject_id: '',
        class_name: '',
        teacher_info: '',
        zhujiao_info: '',
        manager_info: '',
        state: '',
        sort: '',
        value1: [],
        id: ''
      },
      formDateTow: {
        class_name: '',
        subject_id: '',
        state: ''
      },
      options: [],
      optionsTow: [
        { state: 1, label: '显示' },
        {
          state: 2,
          label: '隐藏'
        }
      ],
      tableData: [],
      tableinfo: [],
      zhujiaoinfo: [],
      managerinfo: [],
      page: {
        page: 1, // 当前页码
        total: 10, // 总数
        limit: 10 // 限制条数
      },
      rules: {
        class_name: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
        subject_id: [{ required: true, message: '学科分类不能为空', trigger: 'blur' }]
      },
      dialogshow: true
    }
  },

  created() {
    this.getClass()
    this.subJect()
  },
  methods: {
    handleCurrentChange(val) {
      // val是最新页码数
      this.page.page = val
      // 判断搜索表单是否有数据存在,如果表单内有数据存在，分页切换时要请求的是筛选后的结果
      this.getClass()
    },
    handleSizeChange(val) {
      // 最新页显示条数
      this.page.limit = val
      this.getClass()
    },
    async teacherClass() {
      const { data } = await teacherClass({ role_name: '讲师' })
      this.tableinfo = data
    },
    async zhujiaoClass() {
      const { data } = await zhujiaoClass({ role_name: '助教' })
      this.zhujiaoinfo = data
    },
    async managerClass() {
      const { data } = await managerClass({ role_name: '班主任' })
      this.managerinfo = data
    },
    // 列表加载
    async getClass() {
      const { data } = await getClass(this.page)

      this.tableData = data.list
      this.page.total = data.total
    },
    // 下拉框加载
    async subJect() {
      const { data } = await subJect()
      this.options = data
    },
    // 编辑回显
    async btnEdit(id) {
      this.dialogshow = true
      this.teacherClass()
      this.zhujiaoClass()
      this.managerClass()
      const { data } = await amendClass(id)
      console.log(data)
      this.formDate.id = data.id
      this.dialogFormVisible = true
      console.log(this.formDate.zhujiao_info)
      // 讲师
      this.formDate.teacher_info = JSON.parse(data.teacher_info).map(val => { return val.username })
      console.log(this.formDate.teacher_info)
      // 助教
      this.formDate.zhujiao_info = JSON.parse(data.zhujiao_info).map(val => { return val.username })

      // 班主任
      this.formDate.manager_info = JSON.parse(data.manager_info).map(val => { return val.username })

      this.formDate.value1[1] = data.end_time
      this.formDate.value1[0] = data.start_time
      this.formDate.class_name = data.class_name
      this.formDate.subject_id = data.subject_id
      this.formDate.state = data.state
      this.formDate.sort = data.sort
    },

    // 删除
    async btnDel(id) {
      try {
        await this.$confirm('确认删除员工么')
        await delClass(id)
        if (this.tableData.length === 1 && this.page.page !== 1) {
          this.page.page--
        }
        this.getClass()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 搜索
    async btnSearch() {
      const { data } = await getClass({
        class_name: this.formDateTow.class_name,
        subject_id: this.formDateTow.subject_id,
        page: this.page.page,
        total: this.page.total,
        state: this.formDateTow.state
      })
      // this.getClass()
      this.tableData = data.list
    },
    // 重置按钮
    btnClan() {
      this.formDateTow = {
        class_name: '',
        subject_id: '',
        state: ''
      }
      this.getClass()
    },
    // 状态切换
    async switchChange(id, state) {
      await postStatus({ id: id, state: state })
      this.$message.success('切换成功')
    },
    // 创建班级
    btnAdd() {
      this.dialogshow = true
      this.teacherClass()
      this.zhujiaoClass()
      this.managerClass()
      this.dialogFormVisible = true
    },
    // 弹出层取消
    btnClear() {
      this.dialogshow = false
      this.formDate = {
        subject_id: '',
        class_name: '',
        teacher_info: '',
        zhujiao_info: '',
        manager_info: '',
        state: '',
        sort: '',
        value1: []
      }
      this.dialogFormVisible = false
    },
    // filterObj(data,arr) {
    //  data.forEach(item,index) {
    //  }
    // },
    filterArr(data, array) {
      const arr = []
      data.forEach((key, index) => {
        array.forEach(item => {
          if (index === item) {
            var obj = {}
            // console.log(key)
            obj.username = key.username
            obj.user_id = key.user_id
            arr.push(obj)
          }
        })
      })
      return arr
    },
    // 弹出层ok
    async btnOk() {
      const arr = this.filterArr(this.tableinfo, this.formDate.teacher_info)
      const arr1 = this.filterArr(this.zhujiaoinfo, this.formDate.zhujiao_info)
      const arr2 = this.filterArr(this.managerinfo, this.formDate.manager_info)
      try {
        await this.$refs.formDate.validate()

        if (!this.formDate.id) {
          // 添加
          await AddClass({
            start_time: this.formDate.value1[0],
            end_time: this.formDate.value1[1],
            manager_info: arr2,
            teacher_info: arr,
            zhujiao_info: arr1,
            subject_id: this.formDate.subject_id,
            state: this.formDate.state,
            sort: this.formDate.sort,
            class_name: this.formDate.class_name
          })

          this.getClass()
          this.formDate = {
            subject_id: '',
            class_name: '',
            teacher_info: '',
            zhujiao_info: '',
            manager_info: '',
            state: '',
            sort: '',
            value1: []
          }
          this.$message.success('添加成功')
        } else {
          // 编辑
          await editClass({
            start_time: this.formDate.value1[0],
            end_time: this.formDate.value1[1],
            manager_info: arr2,
            teacher_info: arr,
            zhujiao_info: arr1,
            subject_id: this.formDate.subject_id,
            state: this.formDate.state,
            sort: this.formDate.sort,
            class_name: this.formDate.class_name,
            id: this.formDate.id
          })
          this.$message.success('修改成功')
        }
      } catch (error) {
        console.log(error)
      }
      this.getClass()
      this.dialogFormVisible = false
    }
  }
}
</script>
<style lang="scss" scoped>
.Edit {
  width: 12px;
  height: 12px;
  background-color: red;
}
.demo-table-expand {
  // margin-bottom: 50px;
  padding-left: 20px;
  font-size: 0;
}
.demo-table-expand label {
  width: 100px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 10px;
  width: 34%;
}
.Names {
  padding-left: 30px;
  font-size: 16px;
}
.el-tag.el-tag--success{
  background-color: #e8f4ff;
}
</style>
